package com.shaozi.nc.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.shaozi.nc.quartz.base.Consts;
import com.shaozi.lib.logger.DBLogger;
import com.shaozi.lib.throwable.SzException;

@Component
@Aspect
public class QuartzLogAop {
	private final Logger logger = Logger.getLogger(QuartzLogAop.class);
	@Autowired
	private DBLogger dbLogger;

	public QuartzLogAop() {

	}

	@Pointcut(value = "execution(public void com.shaozi.nc.quartz..*.execute(..))")
	public void cutExecute() {
		// logger.debug("point cut");
	}

	@Before("cutExecute()")
	public void beforeExecute(JoinPoint jp) {
		String logType = jp.getTarget().getClass().getSimpleName();
		String companyId = "";
		String startAt = "";
		if (jp.getArgs().length > 0) {
			if (jp.getArgs()[0] instanceof JobExecutionContext) {
				JobExecutionContext context = (JobExecutionContext) jp.getArgs()[0];
				companyId = context.getJobDetail().getJobDataMap().getString("companyId");
				startAt = context.getJobDetail().getJobDataMap().getString(Consts.DataKey_StartAt);
			}
		}
		dbLogger.save("quartz", logType, "before execute:" + companyId, startAt, 4);
	}

	@After("cutExecute()")
	public void afterExecute(JoinPoint jp) {
		String logType = jp.getTarget().getClass().getName();
		dbLogger.save("quartz", logType, "after execute", null, 4);
	}

	@AfterThrowing(pointcut = "cutExecute()", throwing = "e")
	public void afterThrowing(JoinPoint jp, Exception e) {
		String logType = jp.getTarget().getClass().getName();
		dbLogger.save("quartz", logType, "afterThrowing", SzException.getStackMessage(e), 5);
	}
}
